package com.blog.dao;

import com.blog.bean.QueryCallback;
import com.blog.bean.User;
import com.blog.util.Util;

import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {

    public User selectByPhone(String phone) throws SQLException {
        String sql = "select * from user where phone = '" + phone + "'";
        return (User) JdbcUtil.executeQuery(sql, new QueryCallback() {
            @Override
            public Object doResultHandle(ResultSet resultSet) {
                return transformResult2User(resultSet);
            }
        });
    }

    public void insertUser(String phone, String password) throws SQLException {
        StringBuilder builder = new StringBuilder("insert into user(phone, password, nick, create_time)");
        builder.append("values(");
        builder.append("'").append(phone).append("', ");
        builder.append("'").append(password).append("', ");
        builder.append("'").append("用户" + phone.substring(phone.length() - 4, phone.length())).append("', ");
        String createTime = Util.getNowDateString();
        builder.append("'").append(createTime).append("'");
        builder.append(")");
//        System.out.println(builder.toString());
        JdbcUtil.execute(builder.toString());
    }

    public void updateUser(String nick, String sign, int userId) throws SQLException {
        String sql = "update user set nick = '" + nick + "', sign = '" + sign + "' where id = " + userId;
//        System.out.println(sql);
        JdbcUtil.execute(sql);
    }

    private User transformResult2User(ResultSet resultSet) {
        try {
            if (resultSet == null || !resultSet.next()) {
                return null;
            }
            User user = new User();
            user.setId(resultSet.getInt("id"));
            user.setPhone(resultSet.getString("phone"));
            user.setPassword(resultSet.getString("password"));
            user.setNick(resultSet.getString("nick"));
            user.setImg(resultSet.getString("img"));
            user.setSign(resultSet.getString("sign"));
            user.setCreateTime(resultSet.getDate("create_time"));
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
